﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace RPCenter.UpdaterService.Helper
{
    public class XmlHelper
    {
        #region 根据路径读取XML文件
        /// <summary>
        /// 根据路径读取XML文件
        /// </summary>
        /// <param name="path">xml路径</param>
        /// <returns>返回路径下的所有节点</returns>
        private static XmlDocument GetXmlByPath(string path)
        {
            string url = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + path;
            XmlTextReader reader = new XmlTextReader(url);
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            return doc;
        }
        #endregion

        #region 读取指定节点的值
        /// <summary>
        /// 读取指定节点的值
        /// </summary>
        /// <param name="path">xml路径</param>
        /// <param name="nodeName">节点</param>
        /// <param name="id">节点ID</param>
        /// <returns>返回对应的节点值</returns>
        public static string GetXMLVlueByID(string path, string nodeName, string id)
        {
            XmlNodeList nodeList = GetXmlByPath(path).SelectSingleNode(nodeName).ChildNodes;

            foreach (XmlNode node in nodeList)
            {
                if (node.Attributes["ID"].Value.Trim().ToLower() == id.Trim().ToLower() && node.Attributes["Value"] != null)
                {
                    return node.Attributes["Value"].Value.Trim();
                }
            }
            return "0";
        }
        #endregion

        #region 加载指定的xml文件
        /// <summary>
        /// 加载指定的xml文件
        /// </summary>
        /// <param name="strXmlFilePath"></param>
        /// <returns></returns>
        public static XmlDocument LoadXmlFile(string strXmlFilePath)
        {
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.Load(strXmlFilePath);
            }
            catch (Exception ex)
            {
                throw new Exception("加载菜单xml文件出错：" + ex.Message);
            }
            return xml;
        }
        #endregion

        //反序列化
        //接收2个参数:xmlFilePath(需要反序列化的XML文件的绝对路径),type(反序列化XML为哪种对象类型)
        public static object DeserializeFromXml(string xmlFilePath, Type type)
        {
            object result = null;
            if (File.Exists(xmlFilePath))
            {
                using (StreamReader reader = new StreamReader(xmlFilePath))
                {
                    XmlSerializer xs = new XmlSerializer(type);
                    result = xs.Deserialize(reader);
                }
            }
            return result;
        }

        #region 读取启动文件配置 StartConfig.xml
        /// <summary>
        /// 读取启动文件配置 StartConfig.xml
        /// </summary>
        /// <returns></returns>
        public static StartSet GetStartConfigXml()
        {
            StartSet result = new StartSet();
            string configXmlUrl = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"Config\StartConfig.xml";

            result = DeserializeFromXml(configXmlUrl, typeof(StartSet)) as StartSet;
            
            return result;
        }
        #endregion 
    }

    #region 配置文件实体
    #region  Start.xml
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public class StartSet {
        /// <summary>
        /// 配置更改间隔
        /// </summary>
        public int GlobalIntervalMin { get; set; }
        /// <summary>
        /// 配置节点
        /// </summary>
        public List<StartNode> StartNodeInfo { get; set; }
    }
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public class StartNode {
        /// <summary>
        /// 名字
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// service服务（ApplicationName为服务名） exe应用程序
        /// </summary>
        public string Type { get; set; }
        /// <summary>
        /// 启动程序
        /// </summary>
        public string ApplicationName { get; set; }
        /// <summary>
        /// 间隔时间（分）
        /// </summary>
        public int IntervalMin { get; set; }
        /// <summary>
        /// 文件目录
        /// </summary>
        public string Folder { get; set; } 
        /// <summary>
        /// 剩余时间 分（用于计时）
        /// </summary>
        public int LastMin { get; set; }
        /// <summary>
        /// 显示ui(服务中启动一般只是后台默认运行)
        /// </summary>
        public bool ShowUI { get; set; }
    }
    #endregion
    #endregion
}
